#!/bin/bash

# Property Cleaning System - Docker MySQL Manual Startup Script
# This script provides multiple ways to start MySQL in Docker

set -e

# Color output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# Configuration
MYSQL_CONTAINER_NAME="property-mysql"
MYSQL_ROOT_PASSWORD="root123"
MYSQL_DATABASE="property_cleaning"
MYSQL_USER="property_user"
MYSQL_PASSWORD="property_pass"
MYSQL_PORT="3306"
MYSQL_DATA_DIR="/opt/mysql-data"

# Function to check if Docker is running
check_docker() {
    if ! command -v docker &> /dev/null; then
        echo -e "${RED}Error: Docker is not installed${NC}"
        exit 1
    fi
    
    if ! docker info &> /dev/null; then
        echo -e "${RED}Error: Docker is not running${NC}"
        echo -e "${YELLOW}Please start Docker service first:${NC}"
        echo "  sudo systemctl start docker"
        exit 1
    fi
}

# Function to stop existing MySQL container
stop_existing_mysql() {
    echo -e "${BLUE}Checking for existing MySQL containers...${NC}"
    
    # Stop and remove existing containers with similar names
    docker ps -a --format "table {{.Names}}" | grep -E "mysql|mysql-server|mariadb" | while read container; do
        echo -e "${YELLOW}Stopping existing container: $container${NC}"
        docker stop "$container" 2>/dev/null || true
        docker rm "$container" 2>/dev/null || true
    done
}

# Method 1: Start MySQL with docker run (simple)
start_mysql_simple() {
    echo -e "${GREEN}Starting MySQL with docker run (simple method)...${NC}"
    
    stop_existing_mysql
    
    docker run -d \
        --name "$MYSQL_CONTAINER_NAME" \
        -p "$MYSQL_PORT:3306" \
        -e MYSQL_ROOT_PASSWORD="$MYSQL_ROOT_PASSWORD" \
        -e MYSQL_DATABASE="$MYSQL_DATABASE" \
        -e MYSQL_USER="$MYSQL_USER" \
        -e MYSQL_PASSWORD="$MYSQL_PASSWORD" \
        --restart unless-stopped \
        mysql:8.0
    
    echo -e "${GREEN}MySQL container started successfully!${NC}"
}

# Method 2: Start MySQL with volume persistence
start_mysql_with_volume() {
    echo -e "${GREEN}Starting MySQL with volume persistence...${NC}"
    
    # Create data directory
    sudo mkdir -p "$MYSQL_DATA_DIR"
    sudo chown -R 999:999 "$MYSQL_DATA_DIR"
    
    stop_existing_mysql
    
    docker run -d \
        --name "$MYSQL_CONTAINER_NAME" \
        -p "$MYSQL_PORT:3306" \
        -e MYSQL_ROOT_PASSWORD="$MYSQL_ROOT_PASSWORD" \
        -e MYSQL_DATABASE="$MYSQL_DATABASE" \
        -e MYSQL_USER="$MYSQL_USER" \
        -e MYSQL_PASSWORD="$MYSQL_PASSWORD" \
        -v "$MYSQL_DATA_DIR:/var/lib/mysql" \
        --restart unless-stopped \
        mysql:8.0
    
    echo -e "${GREEN}MySQL container with volume persistence started!${NC}"
}

# Method 3: Start MySQL with docker-compose
start_mysql_compose() {
    echo -e "${GREEN}Starting MySQL with docker-compose...${NC}"
    
    # Create docker-compose.yml
    cat > docker-compose.yml << EOF
version: '3.8'

services:
  mysql:
    image: mysql:8.0
    container_name: $MYSQL_CONTAINER_NAME
    restart: unless-stopped
    environment:
      MYSQL_ROOT_PASSWORD: $MYSQL_ROOT_PASSWORD
      MYSQL_DATABASE: $MYSQL_DATABASE
      MYSQL_USER: $MYSQL_USER
      MYSQL_PASSWORD: $MYSQL_PASSWORD
    ports:
      - "$MYSQL_PORT:3306"
    volumes:
      - mysql_data:/var/lib/mysql
      - ./database/schema.sql:/docker-entrypoint-initdb.d/schema.sql
    command: --default-authentication-plugin=mysql_native_password

volumes:
  mysql_data:
EOF
    
    docker-compose up -d
    echo -e "${GREEN}MySQL started with docker-compose!${NC}"
}

# Function to check MySQL status
check_mysql_status() {
    echo -e "${BLUE}Checking MySQL container status...${NC}"
    
    if docker ps | grep -q "$MYSQL_CONTAINER_NAME"; then
        echo -e "${GREEN}MySQL container is running${NC}"
        
        # Wait for MySQL to be ready
        echo -e "${YELLOW}Waiting for MySQL to be ready...${NC}"
        for i in {1..30}; do
            if docker exec "$MYSQL_CONTAINER_NAME" mysqladmin ping -h localhost -u root -p"$MYSQL_ROOT_PASSWORD" --silent; then
                echo -e "${GREEN}MySQL is ready!${NC}"
                break
            fi
            echo -n "."
            sleep 2
        done
        
        # Show container info
        echo -e "${BLUE}Container information:${NC}"
        docker ps --filter "name=$MYSQL_CONTAINER_NAME" --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
        
        # Test database connection
        echo -e "${BLUE}Testing database connection...${NC}"
        docker exec "$MYSQL_CONTAINER_NAME" mysql -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" -e "SELECT 'Database connection successful' as status;" "$MYSQL_DATABASE" 2>/dev/null && \
            echo -e "${GREEN}Database connection test passed!${NC}" || \
            echo -e "${RED}Database connection test failed${NC}"
    else
        echo -e "${RED}MySQL container is not running${NC}"
    fi
}

# Function to show MySQL logs
show_mysql_logs() {
    echo -e "${BLUE}MySQL container logs:${NC}"
    docker logs "$MYSQL_CONTAINER_NAME" --tail 50
}

# Function to connect to MySQL
connect_mysql() {
    echo -e "${BLUE}Connecting to MySQL...${NC}"
    echo -e "${YELLOW}Available connection methods:${NC}"
    echo "1. From host machine:"
    echo "   mysql -h127.0.0.1 -P$MYSQL_PORT -uroot -p$MYSQL_ROOT_PASSWORD"
    echo "   mysql -h127.0.0.1 -P$MYSQL_PORT -u$MYSQL_USER -p$MYSQL_PASSWORD $MYSQL_DATABASE"
    echo
    echo "2. From inside container:"
    echo "   docker exec -it $MYSQL_CONTAINER_NAME mysql -uroot -p$MYSQL_ROOT_PASSWORD"
    echo "   docker exec -it $MYSQL_CONTAINER_NAME mysql -u$MYSQL_USER -p$MYSQL_PASSWORD $MYSQL_DATABASE"
    echo
    echo "3. Using Docker exec:"
    echo "   docker exec -it $MYSQL_CONTAINER_NAME bash"
}

# Function to stop MySQL
stop_mysql() {
    echo -e "${YELLOW}Stopping MySQL container...${NC}"
    docker stop "$MYSQL_CONTAINER_NAME" 2>/dev/null || true
    echo -e "${GREEN}MySQL container stopped${NC}"
}

# Function to remove MySQL container
remove_mysql() {
    echo -e "${YELLOW}Removing MySQL container...${NC}"
    docker stop "$MYSQL_CONTAINER_NAME" 2>/dev/null || true
    docker rm "$MYSQL_CONTAINER_NAME" 2>/dev/null || true
    echo -e "${GREEN}MySQL container removed${NC}"
}

# Main menu
show_menu() {
    echo
echo "========================================"
echo "  Property Cleaning System - Docker MySQL Manager"
echo "========================================"
echo "MySQL Configuration:"
echo "  Container: $MYSQL_CONTAINER_NAME"
echo "  Port: $MYSQL_PORT"
echo "  Database: $MYSQL_DATABASE"
echo "  User: $MYSQL_USER"
echo "  Root Password: $MYSQL_ROOT_PASSWORD"
echo "========================================"
echo
    echo "Please select an option:"
    echo "1. Start MySQL (simple method)"
    echo "2. Start MySQL (with volume persistence)"
    echo "3. Start MySQL (with docker-compose)"
    echo "4. Check MySQL status"
    echo "5. Show MySQL logs"
    echo "6. Connect to MySQL"
    echo "7. Stop MySQL"
    echo "8. Remove MySQL container"
    echo "9. Exit"
}

# Main execution
main() {
    check_docker
    
    while true; do
        show_menu
        read -p "Enter your choice (1-9): " choice
        
        case $choice in
            1)
                start_mysql_simple
                check_mysql_status
                ;;
            2)
                start_mysql_with_volume
                check_mysql_status
                ;;
            3)
                start_mysql_compose
                check_mysql_status
                ;;
            4)
                check_mysql_status
                ;;
            5)
                show_mysql_logs
                ;;
            6)
                connect_mysql
                ;;
            7)
                stop_mysql
                ;;
            8)
                remove_mysql
                ;;
            9)
                echo "Exiting..."
                exit 0
                ;;
            *)
                echo -e "${RED}Invalid option. Please try again.${NC}"
                ;;
        esac
        
        echo
        read -p "Press Enter to continue..."
    done
}

# Execute main function
main "$@"